<template>
	<view class="l-upload">
		<view class="upload-box">
			<view class="file-item" v-for="(item,index) in fileList" :key="index">
				<block v-if="isVideoOrImage(item) == 'video'">
					<video :src="item" object-fit="cover" class="img" ></video>
					<image src="@/static/user/close.png" class="img-del" @tap="delVideo(index,series)"></image>
				</block>
				<block v-else>
					<image :src="item" class="img" @tap.stop="previewImage(item)" mode="aspectFill"></image>
					<image src="@/static/user/close.png" class="img-del" @tap="delImage(index,series)"></image>
				</block>
			</view>
			<view v-if="isShowAdd" class="upload-add" @tap="chooseFile"></view>
		</view>
	</view>
</template>

<script>
	import base from '@/common/base.js';
	export default {
		name: 'lUpload',
		props: {
			//图片宽度
			width: {
				type: [Number, String],
				default: 220
			},
			//图片高度
			height: {
				type: [Number, String],
				default: 220
			},
			// 上传类型 图片img/视频video  默认都可以
			uploadType:{
				type:String,
				default:'all'
			},
			//禁用添加
			disableAdd: {
				type: Boolean,
				default: false
			},
			//限制数
			limit: {
				type: Number,
				default: 9
			},
			//original 原图，compressed 压缩图，默认二者都有
			sizeType: {
				type: Array,
				default () {
					return ['original', 'compressed']
				}
			},
			//album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
			sourceType: {
				type: Array,
				default () {
					return ['album', 'camera']
				}
			},
			//可上传图片类型，默认为空，不限制  Array<String> ['jpg','png','gif']
			imageFormat: {
				type: Array,
				default () {
					return ['jpg','png','jepg']
				}
			},
			//图片路径
			images: {
				type: Array,
				default () {
					return []
				}
			},
			//视频路径
			videos: {
				type: Array,
				default () {
					return []
				}
			},
			// 文件路径（图片+视频混合）
			files: {
				type: Array,
				default () {
					return []
				}
			},
			series:{
				type:[Number,String],
				default: 0
			}
		},
		data() {
			return {
				// //图片地址
				// imageList: [...this.images],
				// //视频地址
				// videoList: [...this.videos],
				// fileList:[...this.videos,...this.images],

				fileList:[],
				marginRight: 0,

				lineNum: 0,
				videoContext:null,
			}
		},
		watch:{
			files:{
				handler(val){
					this.fileList=val
				},
				deep:true,
				immediate:true,
			},
		},
		computed: {
			isShowAdd() {
				let isShow = true;
				if (this.disableAdd || (this.limit && this.fileList.length >= this.limit)) {
					isShow = false;
				}
				return isShow
			}
		},
		created() {
			// this.initBoxData()
			
		},
		methods: {
			// 判断是视频还是图片
			isVideoOrImage(file) {
				let videoRegex = /(\mp4|\avi|\mkv)$/i
			    let imgRegex = /(\jpg|\jpeg|\png|\gif|\webp)$/i
				if (imgRegex.test(file)) {
					return 'image'
				} else if (videoRegex.test(file)) {
					return 'video'
				} else {
					return 'unknown'
				}
			},

			initBoxData() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.upload-box').fields({
					rect: true, //返回节点布局位置
					size: true //返回节点尺寸
				}, res => {
					let imgwidth = Math.floor(this.width / 2)
					this.lineNum = Math.floor(res.width / imgwidth)
					this.marginRight = (res.width - this.lineNum * imgwidth) / (this.lineNum - 1)
				});
				query.exec(); //执行
			},
			
			chooseFile() {
				if(this.uploadType == 'img'){
					this.chooseImage()
				}else if(this.uploadType == 'video'){
					this.chooseVideo()
				}else{
					uni.showActionSheet({
						itemList: ['图片','视频'],
						success: (res)=> {
							if(res.tapIndex + 1 == 1){
								this.chooseImage()
							}else{
								this.chooseVideo()
							}
						},
						fail: function (res) {
							// console.log(res.errMsg);
						}
					});
				}
				
			},

			chooseVideo() {
				var that = this
				uni.chooseVideo({
					sourceType: ['camera', 'album'],
					success: function(res) {
						let httpsHead = 'https://moyu24h-new.oss-cn-chengdu.aliyuncs.com/'
						that.$tools.loadIng('上传中,请稍后..')
						let video_url = res.tempFilePath
						base.aliyun_upload(video_url, function(r, err) {
							if (r) {
								console.log(httpsHead+r)
								that.video_url = httpsHead+r
								that.fileList = that.fileList.concat(that.video_url);
								uni.hideLoading();
							}
							that.$emit('complete', {
								fileArr: [...that.fileList]
							})
						}, function(res) {
							// console.log(res);
						}, 'mp4', 'video/')
					}
				});
			},

			chooseImage: async function() {
				var that = this
				uni.chooseImage({
					count: that.limit - that.fileList.length,
					extension: ['.jpg', '.png', '.jpeg'],
					success: (res) => {
						console.log(res)
						for (let i in res.tempFilePaths) {
							var imgFiles = res.tempFilePaths[i]
							let suffix = res.tempFilePaths[i].split('.')[1]
							console.log(suffix)
							if (suffix != 'jpg' && suffix != 'png' && suffix != 'jpeg') {
								that.$tools.showToast('图片仅支持jpg、jpeg、png');
								return;
							}
							that.cutImageCallback(imgFiles);
						}
						
						// that.imageList = that.imageList.concat(res.tempFilePaths)
					}
				})
			},
			
			cutImageCallback(content) {
				let that = this;
				let httpsHead = 'https://moyu24h-new.oss-cn-chengdu.aliyuncs.com/'
				that.$tools.loadIng('上传中,请稍后..')
				base.aliyun_upload(content, function(r, err) {
					if (r) {
						let uploadimg = httpsHead + r
						console.log(r)
						that.fileList = that.fileList.concat(uploadimg);
						uni.hideLoading();	
					}
					that.$emit('complete', {
						fileArr: [...that.fileList]
					})
				})	
			},
			
			delVideo(index,series) {
				this.fileList.splice(index, 1)
				this.$emit('remove', {
					fileArr: [...this.fileList],
					series:series
				})
				
				// uni.showModal({
				// 	title: '提示',
				// 	content: '确认删除该视频吗？',
				// 	success: (res) => {
				// 		if (res.confirm) {
				// 			this.fileList.splice(index, 1)
				// 			this.$emit('remove', {
				// 				fileArr: [...this.fileList]
				// 			})
				// 		}
				// 	}
				// })
			},
			delImage(index,series) {
				this.fileList.splice(index, 1)
				
				this.$emit('remove', {
					fileArr: [...this.fileList],
					series:series
				})
				
				// uni.showModal({
				// 	title: '提示',
				// 	content: '确认删除该图片吗？',
				// 	success: (res) => {
				// 		if (res.confirm) {
				// 			this.fileList.splice(index, 1)
				// 			this.$emit('remove', {
				// 				fileArr: [...this.fileList]
				// 			})
				// 		}
				// 	}
				// })
			},
			previewImage(current, urls) {
				let imgUrls = []
				if (!urls) {
					imgUrls.push(current)
				} else {
					imgUrls = urls
				}
				uni.previewImage({
					current,
					urls: imgUrls
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	.l-upload {
		width: 100%;
		.upload-box {
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
			.file-item {
				width: 158rpx;
				height: 158rpx;
				position: relative;
				.img {
					display: block;
					width: 100%;
					height: 100%;
				}
				.img-del {
					position: absolute;
					top: -10upx;	
					right: -10upx;
					width: 40upx;
					height: 40upx;
				}
			}

			.upload-add {
				width: 158rpx;
				height: 158rpx;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				border: 2upx solid #3b4875;
				box-sizing: border-box;
				position: relative;
				&::after {
					content: "";
					display: inline-block;
					width: 40upx;
					height: 4upx;
					background: #3b4875;
					position: absolute;
					left: 0;
					right: 0;
					top: 0;
					bottom: 0;
					margin: auto;
				}
				
				&::before {
					content: "";
					display: inline-block;
					width: 4upx;
					height: 40upx;
					background: #3b4875;
					position: absolute;
					left: 0;
					right: 0;
					top: 0;
					bottom: 0;
					margin: auto;
				}
			}
		}
	}
</style>
